package com.huawei.ds.patch;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.DosFileAttributeView;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class Utils {
    public static void delete(File file) throws IOException {
        Path start = file.toPath();
        if (Files.exists(start, new LinkOption[]{LinkOption.NOFOLLOW_LINKS})) {
            Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    tryDelete(file);
                    return FileVisitResult.CONTINUE;
                }

                public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                    tryDelete(dir);
                    return FileVisitResult.CONTINUE;
                }
            });
        }
    }

    private static void tryDelete(Path path) throws IOException {
        for (int i = 0; i < 10; i++) {
            try {
                if (Files.deleteIfExists(path) || !Files.exists(path, new LinkOption[0])) {
                    PatchMain.logger().info("deleted: " + path);
                    return;
                }
            } catch (AccessDeniedException var5) {

            }
        }
        throw new IOException("Cannot delete: " + path);
    }

    public static InputStream getEntryInputStream(ZipFile zipFile, String entryPath) throws IOException {
        ZipEntry entry = getZipEntry(zipFile, entryPath);
        return findEntryInputStreamForEntry(zipFile, entry);
    }

    public static ZipEntry getZipEntry(ZipFile zipFile, String entryPath) throws IOException {
        ZipEntry entry = zipFile.getEntry(entryPath);
        if (entry == null) throw new IOException("Entry " + entryPath + " not found");
        PatchMain.logger().info("entryPath: " + entryPath);
        return entry;
    }

    public static InputStream findEntryInputStreamForEntry(ZipFile zipFile, ZipEntry entry) throws IOException {
        if (entry.isDirectory()) {
            return null;
        }
        if (zipFile.getEntry(entry.getName() + "/") != null) {
            return null;
        }
        return new BufferedInputStream(zipFile.getInputStream(entry));
    }
}
